package com.bkhech.satoken.controller;

import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.secure.SaSecureUtil;
import lombok.SneakyThrows;

import java.util.HashMap;

/**
 * Sa-Token 密码加解密示例
 *
 * @author guowm
 * @date 2023/8/17
 */
public class SecureController {

    public static void main(String[] args) {
        digest();
        aes();
        rsa();
        base64();
    }

    /**
     * 摘要加密
     */
    public static void digest() {
        System.out.println(SaSecureUtil.md5("123456"));
        System.out.println(SaSecureUtil.sha1("123456"));
        System.out.println(SaSecureUtil.sha256("123456"));
    }

    /**
     * AES 加密
     */
    public static void aes() {
        // 定义秘钥和明文
        String key = "123456";
        String text = "Sa-Token 一个轻量级 java 权限认证框架";

        String cipherText = SaSecureUtil.aesEncrypt(key, text);
        System.out.println("AES 加密后：" + cipherText);

        String text2 = SaSecureUtil.aesDecrypt(key, cipherText);
        System.out.println("AES 解密后：" + text2);
    }

    /**
     * RSA 加密
     */
    @SneakyThrows(value = Exception.class)
    public static void rsa() {
        final HashMap<String, String> keyPair = SaSecureUtil.rsaGenerateKeyPair();
        final String publicKey = keyPair.get("public");
        final String privateKey = keyPair.get("private");
        System.out.println("私钥：" + privateKey);
        System.out.println("公钥：" + publicKey);

        String text = "Sa-Token 一个轻量级 java 权限认证框架";
        final String cipherText = SaSecureUtil.rsaEncryptByPublic(publicKey, text);
        System.out.println("公钥加密后：" + cipherText);

        final String text2 = SaSecureUtil.rsaDecryptByPrivate(privateKey, cipherText);
        System.out.println("私钥解密后：" + text2);
    }

    /**
     * Base64 编码
     */
    public static void base64() {
        String text = "Sa-Token 一个轻量级 java 权限认证框架";

        final String base64Text = SaBase64Util.encode(text);
        System.out.println("Base64 编码后：" + base64Text);

        final String text2 = SaBase64Util.decode(base64Text);
        System.out.println("Base64 解码后：" + text2);
    }

}
